import { createLocalStorage, createSessionStorage } from "./cache/index"
// import { refreshToken } from "@/api/auth"

const TOKEN_CODE = "token"
const ACCESS_TOKEN = "access_token"

export const lsToken = createLocalStorage()
export const SsToken = createSessionStorage()

export function getToken() {
  return SsToken.get(TOKEN_CODE)
}

export function getAccessToken() {
  return SsToken.get(ACCESS_TOKEN)
}

export function setToken(token: string) {
  SsToken.set(TOKEN_CODE, token, null)
}

export function setAccessToken(token: string) {
  SsToken.set(ACCESS_TOKEN, token, null)
}

export function removeToken() {
  SsToken.remove(TOKEN_CODE)
}

export function removeAccessToken() {
  SsToken.remove(ACCESS_TOKEN)
}

export async function refreshAccessToken() {
  const tokenItem = lsToken.getItem(TOKEN_CODE)
  if (!tokenItem) return

  const { time } = tokenItem
  if (new Date().getTime() - time > 1000 * 60 * 30) {
    try {
      const res = await refreshToken()
      if (res.code === 0) setToken(res.data.token)
    } catch (error) {
      console.error(error)
    }
  }
}
